package cn.chmcyz.bootredis.service.impl;

import cn.chmcyz.bootredis.common.Constants;
import cn.chmcyz.bootredis.common.Result;
import cn.chmcyz.bootredis.filter.RedisBloomFilter;
import cn.chmcyz.bootredis.mapper.EmployeeMapper;
import cn.chmcyz.bootredis.model.Employee;
import cn.chmcyz.bootredis.service.IEmployeeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chm
 * @since 2020-12-20
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private RedisBloomFilter redisBloomFilter;

    @Override
    public Result selectById(Integer id) {
        //布隆过滤器解决缓存穿透
        if (!redisBloomFilter.exists("" + id)) {
            return Result.failed("非法访问");
        }
        //判断缓存有没有
        Object obj = redisTemplate.opsForValue().get(Constants.EMP_REDIS_KEY_PREFIX + id);
        if (obj != null) {
            System.out.println("命中缓存");
            return Result.sucess((Employee)obj);
        }
        System.out.println("查库");
        //缓存没有查库
        Employee employee = baseMapper.selectById(id);
        //放入缓存
        redisTemplate.opsForValue().set(Constants.EMP_REDIS_KEY_PREFIX + id, employee);
        return Result.sucess(employee);
    }
}
